package com.micro.service.auth.server.login.wechat;

import com.micro.service.account.share.service.UserBaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;

/**
 * @author lvxiucai
 * @description 微信登录配置
 * @date 2019/9/25
 */
@Component
public class WechatAuthenticationSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

    @Autowired
    private AuthenticationSuccessHandler loginSuccessHandler;

    @Autowired
    private AuthenticationFailureHandler loginFailureHandler;

    @Autowired
    private UserBaseService userBaseService;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        WechatAuthenticationFilter wechatAuthenticationFilter = new WechatAuthenticationFilter();
        wechatAuthenticationFilter.setUserBaseService(userBaseService);
        wechatAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
        wechatAuthenticationFilter.setAuthenticationFailureHandler(loginFailureHandler);
        wechatAuthenticationFilter.setAuthenticationSuccessHandler(loginSuccessHandler);

        WechatAuthenticationProvider wechatAuthenticationProvider = new WechatAuthenticationProvider();
        wechatAuthenticationProvider.setUserBaseService(userBaseService);
        http.authenticationProvider(wechatAuthenticationProvider)
                .addFilterAfter(wechatAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    }


}
